package com.fbs.wowo.wx.web;


import com.fbs.wowo.base.BaseController;
import com.fbs.wowo.base.Response;
import com.fbs.wowo.exception.DataOverflowException;
import com.fbs.wowo.exception.ErrorCode;
import com.fbs.wowo.manage.entity.Account;
import com.fbs.wowo.manage.mapper.AccountMapper;
import com.fbs.wowo.util.eos.EOSService;
import com.fbs.wowo.util.eos.EOSServiceImp;
import com.fbs.wowo.util.upload.Oss;
import com.fbs.wowo.util.watermark.QrCodeUtil;
import com.fbs.wowo.util.watermark.WaterMarkUtils;
import com.fbs.wowo.wx.entity.WxAuth;
import com.fbs.wowo.wx.service.WxAuthService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.swing.filechooser.FileSystemView;
import java.io.File;
import java.io.FileInputStream;
import java.time.LocalDate;
import java.util.List;

@RestController
@RequestMapping("/wx")
public class WxAuthController  extends BaseController {

    @Resource
    private WxAuthService wxAuthService;

    @Resource
    private EOSService eosService;

    @Resource
    private AccountMapper accountMapper;

    @Value("${HOST_ADDRESS}")
    private String HOST_ADDRESS;


    @GetMapping("findByUserId")
    public Response findByUserId(String userId,int pageNum,int pageSize){
        PageHelper.startPage(pageNum, pageSize);
        List<WxAuth> list = wxAuthService.findWxAuthByUserId(userId);
        PageInfo<WxAuth> pageInfo = new PageInfo<>(list);
        return success(pageInfo);
    }

    @PostMapping("insert")
    public Response insert(WxAuth wxAuth){
        return success(wxAuthService.insertSelective(wxAuth));
    }

    @PostMapping("success")
    public Response success(@RequestBody String postData) throws Exception {
        System.out.println("进入success");
        System.out.println("postData:"+postData);
        JSONObject jsonObject = JSONObject.fromObject(postData);
        String cmdId = jsonObject.get("cmdId").toString();
        WxAuth wxAuth = wxAuthService.selectByPrimaryKey(cmdId);
        if (wxAuth != null) {
            String filepath = jsonObject.get("filePath").toString();
            File file = new File(filepath);
            FileInputStream input = new FileInputStream(file);
            MultipartFile multipartFile = new MockMultipartFile
                    (cmdId+".zip", cmdId+".zip", "text/pain", input);
            String imgUrl = Oss.getFileUrl(multipartFile, "微信文章确权文件", Oss.getOssEndpointPrivate(),
                    Oss.getOssAccessKeyId(), Oss.getOssAccessKeySecret(), Oss.getOssBucketName());

            if (imgUrl!=null && !imgUrl.equals("")){
                if (file.exists() && file.isFile()) {
                    file.delete();
                    wxAuth.setFilePath(imgUrl);
                    wxAuth.setHashValue(jsonObject.get("sha256").toString());
                    wxAuth.setState((byte)2);

                    Account account = accountMapper.findByUserId(wxAuth.getUserId());
                    if (account!=null){
                        //登记
                        eosService.imagetextEvidence
                                (wxAuth.getUserId(),account.getPrivateKey(),"微信公众号端",wxAuth.getWxArticleName(),wxAuth.getAuthorName(),wxAuth.getAuthorName(),wxAuth.getHashValue()," ");
                        //确权
                        EOSServiceImp.EosTransactionResponse eos =
                                eosService.imagetextAuthright(wxAuth.getUserId(), account.getPrivateKey(), wxAuth.getHashValue());

                        wxAuth.setBlockHeight(eos.getBlockNum());
                        wxAuth.setRegisterId(eos.getTransactionId());
                        wxAuth.setChainId(eos.getChainId());

                        LocalDate now = LocalDate.now();
                        int year = now.getYear();
                        int month = now.getMonthValue();
                        int day = now.getDayOfMonth();
                        String date = year + "年" + month + "月" + day + "日";

                        //二维码
                        String infoUrl = HOST_ADDRESS + "wx/dataDetail?essayId=" + wxAuth.getId();
                        String path = FileSystemView.getFileSystemView().getHomeDirectory() + File.separator + "testQrcode";
                        String fileName = cmdId+".jpg";
                        String smallImgPath = QrCodeUtil.createQrCode(infoUrl, path, fileName);

                        String url = WaterMarkUtils.addWaterMark
                                //二维码,作品名称,类别名称,作者,归属人,认证时间
                                        (smallImgPath, wxAuth.getHashValue(), wxAuth.getWxArticleName(), "图文作品", wxAuth.getAuthorName(), wxAuth.getAuthorName(), date);
                        wxAuth.setCertificateImg(url);

                        File file1 = new File(smallImgPath);
                        if (file1.exists() && file1.isFile()) {
                            file1.delete();
                            wxAuthService.updateByPrimaryKeySelective(wxAuth);
                            System.out.println("完成success!");
                            return success();
                        }
                        throw new DataOverflowException(ErrorCode.ERR_FILE_NULL);
                    }
                    throw new DataOverflowException(ErrorCode.ERR_RED_FROM_ACCOUNT_NULL);   //账户不存在
                }
                throw new DataOverflowException(ErrorCode.ERR_FILE_NULL);   //文件不存在
            }
            throw new DataOverflowException(ErrorCode.ERR_UPLOAD);      //上传失败
        }
        throw new DataOverflowException(ErrorCode.ERR_USER_NOT_EXIST);  //确权数据不存在
    }


}
